package com.itheima;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/servletDemo1")
public class ServletDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext servletContext = getServletContext();
        String name = request.getParameter("name");
        String realPath = servletContext.getRealPath("ziyuan/" + name);
        FileInputStream is=new FileInputStream(realPath);
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("content-disposition","attachment;filename="+name);
        byte[] bytes=new byte[1024];
        int len;
        while ((len=is.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        is.close();
    }
}